package com.m1905hd.web.controller

import com.m1905hd.common.global.JSONCode
import com.m1905hd.common.util.Page
import com.m1905hd.service.ImgService
import com.mongodb.BasicDBObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.multipart.MultipartFile


/**
 * Created by sunhao on 2016/12/15.
 */
@Controller
@RequestMapping(value = "image")
class ImgController {

    static final BOOT_PATH = "/home"

    @Autowired
    ImgService imgService

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    def showList() {
        return "image/list"
    }


    @RequestMapping("upload")
    def upload(String title, MultipartFile file) {
        if (file) {
            try {
//                MultipartFile multipartFile = file
//                String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
//                def now = System.currentTimeMillis() + ""
//                File temp = File.createTempFile(now, suffix)
//                multipartFile.transferTo(temp);
                String path = this.imgService.uploadImg(file)
                if (!path.startsWith("/")) {
                    path = BOOT_PATH + "/" + path
                }
                def info = [title: title, img: path, type: 0, created: System.currentTimeMillis()] as BasicDBObject
                this.imgService.update(UUID.randomUUID().toString().replaceAll("-", ""), info)
            } catch (Exception e) {
                e.printStackTrace()
            }
        }
        return "image/list"
    }

    @RequestMapping(value = "/list.json")
    def list(
            @RequestParam(defaultValue = "15") int limit,
            @RequestParam(defaultValue = "0") int pageIndex,
            String title
    ) {
        pageIndex = pageIndex + 1
        def query = [type: 0] as BasicDBObject
        if (!StringUtils.isEmpty(title)) {
            query.append("title", ~/${title}/)
        }
        Page page = this.imgService.list(query, new BasicDBObject("created", -1), null, pageIndex, limit)
        [results: page.count, rows: page.data]
    }


    @RequestMapping("delete.json")
    def del(String ids) {
        ids.split(",").each {
            if (!StringUtils.isEmpty(it)) {
                this.imgService.del(it)
            }

        }
        return [code: JSONCode.SUCCESS.code]
    }
}
